#include "webserver.h"
using namespace std;



static EventLoop *CheckLoopNotNull(EventLoop *loop)
{
    if (loop == nullptr)
    {
        LOG_ERROR("main Loop is NULL!");
    }
    return loop;
}
WebServer::WebServer(
        EventLoop *loop,
        const InetAddress &listenAddr,
        const std::string &nameArg,
        int sqlPort, const char* sqlUser, const  char* sqlPwd, 
        const char* dbName, int connPoolNum, 
        int threadNum,
        bool openLog, int logLevel, int logQueSize):
        loop_(CheckLoopNotNull(loop))
        , ipPort_(listenAddr.toIpPort())
        , name_(nameArg)
        , acceptor_(new Acceptor(loop, listenAddr,kReusePort))
        , threadPool_(new EventLoopThreadPool(loop, name_))
        , connectionCallback_()
        , messageCallback_()
        , started_(0)
        , nextConnId_(1)
    {
        srcDir_ = getcwd(nullptr, 256);
        assert(srcDir_);
        strncat(srcDir_, "/resources/", 16);
        HttpConn::userCount = 0;
        HttpConn::srcDir = srcDir_;
        /*没用上*/
        SqlConnPool::Instance()->Init("localhost", sqlPort, sqlUser, sqlPwd, dbName, connPoolNum);
        /*服务器的socketfd在Accepter中*/
        if(openLog) {
            Log::Instance()->init(logLevel, "./log", ".log", logQueSize);
            {
                LOG_INFO("========== Server init ==========");
                LOG_INFO("Port:%s",ipPort_.c_str());
                LOG_INFO("LogSys level: %d", logLevel);
                LOG_INFO("srcDir: %s", HttpConn::srcDir);
                LOG_INFO("SqlConnPool num: %d, ThreadPool num: %d", connPoolNum, threadNum);
            }
        }
        LOG_INFO("Server fd:[%d]",acceptor_->getAcceptorId());
        acceptor_->setNewConnectionCallback(
        std::bind(&WebServer::newConnection, this, std::placeholders::_1, std::placeholders::_2));
}

WebServer::~WebServer() {
    for(auto &item : connections_)
    {
        HttpConnPtr conn(item.second);
        item.second.reset();    // 把原始的智能指针复位 让栈空间的TcpConnectionPtr conn指向该对象 当conn出了其作用域 即可释放智能指针指向的对象
        // 销毁连接(在回调函数中这件事)
        conn->getLoop()->runInLoop(
            std::bind(&HttpConn::connectDestroyed, conn));
    }
}

// 设置底层subloop的个数
void WebServer::setThreadNum(int numThreads)
{
    int numThreads_=numThreads;
    threadPool_->setThreadNum(numThreads_);
}

void WebServer::Start() {
    
    if (started_.fetch_add(1) == 0)    // 防止一个TcpServer对象被start多次
    {
        threadPool_->start(threadInitCallback_);    // 启动底层的loop线程池
        /*在这个回调函数中启动了epoll监听fd可读*/
        loop_->runInLoop(std::bind(&Acceptor::listen, acceptor_.get()));
    }
}
// 有一个新用户连接，acceptor会执行这个回调操作，负责将mainLoop接收到的请求连接(acceptChannel_会有读事件发生)通过回调轮询分发给subLoop去处理
void WebServer::newConnection(int sockfd, const InetAddress &peerAddr)
{
   // 轮询算法 选择一个subLoop 来管理connfd对应的channel
    EventLoop *ioLoop = threadPool_->getNextLoop();
    char buf[64] = {0};
    snprintf(buf, sizeof buf, "-%s#%d", ipPort_.c_str(), nextConnId_);
    ++nextConnId_;  // 这里没有设置为原子类是因为其只在mainloop中执行 不涉及线程安全问题
    std::string connName = name_ + buf;

    //LOG_INFO("TcpServer::newConnection [%s] new connection[%s] peerAddr.toIpPort():[%s]",name_.c_str(),connName.c_str(),peerAddr.toIpPort().c_str());
    //LOG_INFO("ioLoop::[%p]",ioLoop);
    // 通过sockfd获取其绑定的本机的ip地址和端口信息
    sockaddr_in local;
    ::memset(&local, 0, sizeof(local));
    socklen_t addrlen = sizeof(local);
    if(::getsockname(sockfd, (sockaddr *)&local, &addrlen) < 0)
    {
        LOG_ERROR("sockets::getLocalAddr");
    }

    InetAddress localAddr(local);
    HttpConnPtr conn(new HttpConn(ioLoop,sockfd, connName,
                                localAddr,peerAddr));
    connections_[connName] = conn;
    // 下面的回调都是用户设置给TcpServer => TcpConnection的，至于Channel绑定的则是TcpConnection设置的四个，handleRead,handleWrite... 这下面的回调用于handlexxx函数中
    conn->setConnectionCallback(connectionCallback_);
    conn->setMessageCallback(messageCallback_);
    conn->setWriteCompleteCallback(writeCompleteCallback_);

    // 设置了如何关闭连接的回调
    // 关闭连接只能由主线程来关闭
    conn->setCloseCallback(
        std::bind(&WebServer::removeConnection, this, std::placeholders::_1));

    ioLoop->runInLoop(
        std::bind(&HttpConn::connectEstablished, conn));
}

void WebServer::removeConnection(const HttpConnPtr &conn)
{
    loop_->runInLoop(
        std::bind(&WebServer::removeConnectionInLoop, this, conn));
}

void WebServer::removeConnectionInLoop(const HttpConnPtr &conn)
{
    LOG_INFO("TcpServer::removeConnectionInLoop [%s]",name_.c_str(),
            "connection %s",conn->name().c_str());

    connections_.erase(conn->name());
    EventLoop *ioLoop = conn->getLoop();
    ioLoop->queueInLoop(
        std::bind(&HttpConn::connectDestroyed, conn));
}